package com.neuedu.mblog.filter;

import com.alibaba.fastjson.JSON;
import com.neuedu.mblog.entiry.User;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * 项目：his
 * 创建时间：  2021/12/14   13:34
 * 作者 :jshand
 * 描述 : 登录的过滤器
 */
public class LoginFilter implements Filter {


    String[] validUrls ={ "/admin" ,"/user"  ,"/post"  ,"/front/user"};



    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    /**
     * 每一次请求时调用
     * @param req   HttpServletRequest
     * @param resp  HttpServletResponse
     * @param chain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        HttpSession session = request.getSession();


        //admin开头的路径
        User user  = (User) session.getAttribute("user");
        if(validateUrl(request) && user == null  ){
            //登录失败，记录失败的消息， 跳转到 login.jsp
            ///front/user
            String contextPath =  request.getContextPath();
            String uri = request.getRequestURI();
            uri = uri.substring(contextPath.length()); //index.html
            if("/front/user".equals(uri)){
                //如果是ajax 访问，则返回401 未登录
                Map map  = new HashMap();
                map.put("success",false);
                map.put("code",401);
                map.put("msg","登录超时,请登录");

                String json = JSON.toJSONString(map);
                PrintWriter out = response.getWriter();
                out.write(json);
                out.flush();
                out.close();
            }else{
                response.sendRedirect(request.getContextPath()+"/login.jsp");
            }

        }else{  //需要登录
            //放行
            chain.doFilter(req,resp);
        }
    }




    public boolean validateUrl(HttpServletRequest request) {
        String contextPath =  request.getContextPath();
        String uri = request.getRequestURI();
        uri = uri.substring(contextPath.length()); //index.html

        for (String validUrl : validUrls) {
            if(uri.startsWith(validUrl)){
                return true;
            }
        }
        return false;

    }




    /**
     * 销毁的时候调用，
     */
    @Override
    public void destroy() {

    }
}
